package com.lanp.native_test.controller;

import java.util.UUID;
import java.util.function.Function;

public class LambdaTest {
    public static void main(String[] args) {
        int a = 10;
        Result<Integer> run1 = run((params) -> params + 1, a);
        System.out.println("执行结果1-" + run1.toStringInfo());
        int b = 5;
        Result<Integer> run2 = run((params) -> params / 0, b);
        System.out.println("执行结果2-" + run2.toStringInfo());


        System.out.println(UUID.randomUUID().toString());

        int a1 = 10, a2 = 33, a3 = 561;
        Result<Integer> run11 = run2((t, p, p2) -> t - p + p2, a1, a2, a3);
        System.out.println("执行结果22-" + run11.toStringInfo());
        System.out.println("执行结果22-" + run11.getData().intValue());

    }

    @FunctionalInterface
    public interface CustomFunction<T, P, P2, R> {
        R apply(T t, P p, P2 p2);
    }


    public static class Result<R> {
        private String msg;
        private int code;
        private R data;

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public R getData() {
            return data;
        }

        public void setData(R data) {
            this.data = data;
        }


        public String toStringInfo() {
            return "data:" + data
                    + "\tcode:" + this.code
                    + "\tmsg:" + this.msg;
        }

        public static <R> Result<R> succ(R r) {
            Result res = new Result();
            res.setCode(200);
            res.setData(res);
            res.setMsg("成功");
            return res;
        }

        public static <R> Result<R> error(R r) {
            Result res = new Result();
            res.setCode(200);
            res.setData(r);
            res.setMsg("成功");
            return res;
        }

        public static <R> Result<R> error(String msg) {
            Result res = new Result();
            res.setCode(400);
            res.setMsg(msg);
            return res;
        }
    }

    public static <T, R> Result<R> run(Function<T, R> func, T params) {
        try {
            R res = func.apply(params);
            return Result.succ(res);
        } catch (Exception e) {
            System.out.println("执行异常" + e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    public static <T, P, P2, R> Result<R> run2(CustomFunction<T, P, P2, R> func, T t, P p, P2 p2) {
        try {
            R res = func.apply(t, p, p2);
            return Result.succ(res);
        } catch (Exception e) {
            System.out.println("执行异常" + e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
